<?php
namespace Service;

class Sign extends Base
{

    public function getSignAppKey()
    {
        $config = getConfig('sign', THE_DEFAULT);
        return $config['app_key'];
    }

    public function getSign($array, $appKey = '')
    {
        $appKey = $this->tryGet($appKey);
        $array['appKey'] = $appKey;
        ksort($array);
        $list = [];
        foreach($array as $k => $v){
            if(is_array($v)){
                $v = json_encode($v);
            }
            $list[] = $v;
        }
        $list = implode('', $list);
        return md5($list);
    }

    public function checkSign($array, $appKey = '')
    {
        $appKey = $this->tryGet($appKey);
        if(!isset($array['sign'])){
            return false;
        }
        $sign1 = $array['sign'];
        unset($array['sign']);
        $sign2 = $this->getSign($array, $appKey);
        return $sign1 == $sign2;
    }

    public function tryGet($appKey)
    {
        if(!empty($appKey)){
            return $appKey;
        }
        return $this->getSignAppKey();
    }

}